import {Component, OnInit} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {FormObjModel} from '../formObj.model';
import {RequestForServiceService} from '../request-for-service.service';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {PublicService} from '../../services/public.service';
import {PUblicMethod} from '../../services/PUblicMethod';
import {StorageService} from '../../services/storage.service';
import {Message, TreeNode} from 'primeng/primeng';
import {environment} from '../../../environments/environment';
import {EventBusService} from '../../services/event-bus.service';

@Component({
  selector: 'app-add-or-edit-service',
  templateUrl: './add-or-edit-service.component.html',
  styleUrls: ['./add-or-edit-service.component.scss']
})
export class AddOrEditServiceComponent implements OnInit {
    formObj: FormObjModel;
    myForm: FormGroup;
    dropdownOption = {
        fromx: [],
        type: [],
        bt_system: [],
        influence: [],
        urgency: [],
        acceptor: []
    };
    displayPersonel: boolean = false;              // 人员组织组件是否显示
    zh: Object;
    message: Message[] = [];               // 交互提示弹出框
    ip: string;
    display: boolean = false;
    filesTree4: TreeNode[] = [];
    selected: Array<any> = [];
    formTitle: string;

    constructor(private activatedRouter: ActivatedRoute,
        private router: Router,
        private rfsService: RequestForServiceService,
        private publicService: PublicService,
        private eventBusService: EventBusService,
        private storageService: StorageService,
        private fb: FormBuilder) {
    }
    ngOnInit() {
        this.formObj = new FormObjModel();
        this.createForm();
        this.getOptions();
        this.getUser();
        this.getDepPerson();
        this.zh = new PUblicMethod().initZh();
        this.formObj.sid = this.activatedRouter.snapshot.paramMap.get('id');
        this.formObj.status = '新建';
        this.formTitle = '创建服务请求';
        this.formObj.create_time = PUblicMethod.formateEnrtyTime( new Date() );
        this.formObj.occurrence_time = PUblicMethod.formateEnrtyTime( new Date() );
        this.fb = new FormBuilder();
        this.ip = environment.url.management;
        if (this.formObj.sid) {
            this.formTitle = '编辑服务请求';
            this.formObj.status = this.activatedRouter.snapshot.paramMap.get('status');
            this.getTirckMessage(this.formObj.sid);
            this.rfsService.getFlowChart(this.formObj.status).subscribe(res => {
                this.eventBusService.rfs.next(res);
            });
        }
    }
    goBack() {
        this.router.navigate(['../serviceOverview'], {relativeTo: this.activatedRouter});
    }
    getUser() {
        this.publicService.getUser().subscribe(res => {
           this.formObj.creator = res.name;
        });
    }
    createForm() {
        this.myForm = this.fb.group({
            'fromx': '',
            'type': '',
            'submitter': '',
            'title': '',
            'content': '',
            'acceptor': ''
        });
    }
    getOptions() {
        this.rfsService.getParamOptions().subscribe(res => {
            if (!this.formObj.sid) {
                this.getPrority(res['影响度'][0]['name'], res['紧急度'][0]['name']);
            }
            this.dropdownOption['fromx'] = PUblicMethod.formateDropDown(res['来源']);
            this.dropdownOption['type'] = PUblicMethod.formateDropDown(res['服务类型']);
            this.dropdownOption['bt_system'] = PUblicMethod.formateDropDown(res['所属系统']);
            this.dropdownOption['influence'] = PUblicMethod.formateDropDown(res['影响度']);
            this.dropdownOption['urgency'] = PUblicMethod.formateDropDown(res['紧急度']);
            this.formObj.fromx = res['来源'][0]['name'];
            this.formObj.type = res['服务类型'][0]['name'];
            this.formObj.bt_system = res['所属系统'][0]['name'];
            this.formObj.influence = res['影响度'][0]['name'];
            this.formObj.urgency = res['紧急度'][0]['name'];
        });
    }
    showTreeDialog( opType ) {
        switch (opType) {
            case 'submitter':
                this.displayPersonel = true;
                break;
            case 'department':
                this.display = true;
                this.publicService.getDepartmentDatas().subscribe(res => {
                    this.filesTree4 = res;
                });
        }

    }
    clearTreeDialog(opType) {
        switch (opType) {
            case 'submitter':
                this.formObj.submitter = '';
                this.formObj.submitter_pid = '';
                this.formObj.submitter_org_oid = '';
                this.formObj.submitter_org = '';
                this.formObj.submitter_phone = '';
                break;
            case 'department':
                this.formObj.acceptor = '';
                this.formObj.acceptor_org = '';
                this.formObj.acceptor_org_oid = '';
                this.formObj.acceptor_pid = '';
                break;
        }

    }
    dataEmitter(event) {
        this.formObj.submitter = event.name;
        this.formObj.submitter_pid = event.pid;
        this.formObj.submitter_org_oid = event.oid;
        this.formObj.submitter_org = event.organization;
        this.formObj.submitter_phone = event.mobile;
    }
    displayEmitter(event) {
        this.displayPersonel = event;
    }
    onFocus() {
        if (this.formObj.influence['name']) {
            this.formObj.influence = this.formObj.influence['name'];
        }
        if (this.formObj.urgency['name']) {
            this.formObj.urgency = this.formObj.urgency['name'];
        }
        this.getPrority(this.formObj.influence, this.formObj.urgency);
    }
    getPrority(influency, urgency) {
        if ( influency && urgency ) {
            this.rfsService.getPrority( influency, urgency ).subscribe(res => {
                if (res) {
                    this.formObj.priority = res['priority'];
                    this.getDeadline(influency, urgency, res['priority']);
                }
            });
        }
    }
    getDeadline(influency, urgency, prority) {
        if ( influency && urgency && prority ) {
            this.rfsService.getDeadline( influency, urgency, prority, this.formObj.create_time).subscribe(res => {
                if (res) {
                    this.formObj.deadline = res['time_deadline'];
                }
            });
        }
    }
    onBeforeUpload(event) {
        let token = this.storageService.getToken('token');
        event.formData.append('access_token', token);
    }
    onUpload(event) {
        let xhrRespose = JSON.parse(event.xhr.response);
        if ( xhrRespose.errcode && xhrRespose.errcode === '00000' ) {
            this.formObj.attachments = xhrRespose['datas'];
            this.message = [];
            this.message.push({severity: 'success', summary: '消息提示', detail: '上传成功'});
        }else {
            this.message = [];
            this.message.push({severity: 'error', summary: '消息提示', detail: `上传失败${xhrRespose.errmsg}`});
        }
    }
    nodeExpand(event) {
        if (event.node) {
            this.publicService.getDepartmentDatas(event.node.oid, event.node.dep).subscribe(res => {
                event.node.children  = res;
            });
        }
    }
    closeTreeDialog() {
        this.display = false;
        this.formObj.acceptor_org = this.selected['label'];
        this.formObj.acceptor_org_oid = this.selected['oid'];
        this.getDepPerson(this.selected['oid']);
    }
    getDepPerson(oid?) {
        this.publicService.getApprovers(oid).subscribe(res => {
            (!res) && (this.dropdownOption.acceptor = []);
            if (res) {
                this.dropdownOption.acceptor = PUblicMethod.formateDepDropDown(res);
                this.formObj.acceptor_pid = res[0]['pid'];
                this.formObj.acceptor = res[0]['name'];
            }
        });
    }
    restOccurTime() {
        this.formObj.occurrence_time = PUblicMethod.formateEnrtyTime(this.formObj.occurrence_time);
    }
    save() {
        this.restOccurTime();
        this.onSelectedDepartment();
        this.rfsService.saveTicket( this.formObj ).subscribe(res => {
            if ( res === '00000' ) {
                this.message = [];
                this.message.push({severity: 'success', summary: '消息提示', detail: '保存成功'});
                window.setTimeout(() => {
                    this.router.navigateByUrl('/index/reqForService/rfsBase/serviceOverview');
                }, 1100);
            }else {
                this.message = [];
                this.message.push({severity: 'error', summary: '消息提示', detail: `保存失败${res}`});
            }
        });
    }
    submitTrick() {
        if ( !this.formObj.submitter
            || !this.formObj.title
            || !this.formObj.content
        ) {
            this.showError();
            this.setValidators();
        }else {
            this.formObj.status = '待分配';
            this.onSelectedDepartment();
            this.submitPost(this.formObj);
        }
    }
    showError() {
        this.message = [];
        this.message.push({severity: 'error', summary: '错误消息提示', detail: '请填写完整表单'});
    }
    get Submitter() {
        return this.myForm.controls['submitter'].untouched && this.myForm.controls['submitter'].hasError('required');
    }
    get title() {
        return this.myForm.controls['title'].untouched && this.myForm.controls['title'].hasError('required');
    }
    get content() {
        return this.myForm.controls['content'].untouched && this.myForm.controls['content'].hasError('required');
    }
    get acceptor() {
        return this.myForm.controls['acceptor'].untouched && this.myForm.controls['acceptor'].hasError('required');
    }
    setValidators() {
        this.myForm.controls['submitter'].setValidators([Validators.required]);
        this.myForm.controls['title'].setValidators([Validators.required]);
        this.myForm.controls['content'].setValidators([Validators.required]);
        this.myForm.controls['submitter'].updateValueAndValidity();
        this.myForm.controls['title'].updateValueAndValidity();
        this.myForm.controls['content'].updateValueAndValidity();
    }
    submitPost(paper) {
        this.rfsService.submitTicket( paper ).subscribe(res => {
            if ( res === '00000' ) {
                this.message = [];
                this.message.push({severity: 'success', summary: '消息提示', detail: '操作成功'});
                window.setTimeout(() => {
                    this.router.navigateByUrl('/index/reqForService/rfsBase/serviceOverview');
                }, 1100);
            }else {
                this.message = [];
                this.message.push({severity: 'error', summary: '消息提示', detail: `操作失败${res}`});
            }
        });
    }
    submitAndDistribute() {
        if ( !this.formObj.submitter
            || !this.formObj.title
            || !this.formObj.content
            || !this.formObj.acceptor_org
        ) {
            this.showError();
            this.setValidators();
            this.myForm.controls['acceptor'].setValidators([Validators.required]);
            this.myForm.controls['acceptor'].updateValueAndValidity();
        }else {
            this.formObj.status = '待接受';
            this.onSelectedDepartment();
            this.restOccurTime();
            this.submitPost(this.formObj);
        }
    }
    getTirckMessage(sid) {
        this.rfsService.getTrick(sid).subscribe(res => {
            this.formObj = new FormObjModel(res);
        });
    }
    onSelectedDepartment() {
        if (typeof this.formObj.acceptor === 'object') {
           this.formObj.acceptor_pid = this.formObj.acceptor['pid'];
           this.formObj.acceptor = this.formObj.acceptor['name'];
        }
    }


}
